/**
 * 
 */
package org.t2.backstage.module.player;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.banish.sql.core.util.QuerySet;
import org.gaming.backstage.PageData;
import org.gaming.service.apidoc.annotation.ApiDocument;
import org.gaming.tool.DateTimeUtil;
import org.gaming.tool.ListMapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.t2.backstage.module.gameserver.model.GameChannel;
import org.t2.backstage.module.gameserver.service.GameChannelService;
import org.t2.backstage.module.player.model.PlayerSummary;
import org.t2.backstage.module.player.query.PlayerCommonQuery;
import org.t2.backstage.module.player.service.PlayerPayInServerService;
import org.t2.backstage.module.player.service.PlayerSummaryService;
import org.t2.backstage.module.player.vo.PlayerSummaryVo;

/**
 * 基础数据（角色）
 */
@Controller
public class PlayerSummaryController {
	
	@Autowired
	private PlayerSummaryService playerSummaryService;
	@Autowired
	private GameChannelService gameChannelService;
	@Autowired
	private PlayerPayInServerService playerPayInServerService;
	
	
	@ApiDocument("基础数据（角色）")
	@RequestMapping(value = "/playerSummary/data.auth")
	@ResponseBody
	public PageData<PlayerSummaryVo> data(PlayerCommonQuery query) {
		QuerySet querySet = new QuerySet();
		//渠道选择
		if(query.getChannels() != null && !query.getChannels().isEmpty()) {
			querySet.findInSet("channel_id", query.getChannels());
		}
		//服务器选择
		if(query.getServerUids() != null && !query.getServerUids().isEmpty()) {
			querySet.findInSet("server_uid", query.getServerUids());
		}
		//开始时间
		long startTime = query.getStartTime() * 1000L;
		if(startTime == 0) {
			startTime = DateTimeUtil.monthZeroMillis();
		}
		String startBorn = DateTimeUtil.formatMillis(DateTimeUtil.YYYYMMDD, startTime);
		querySet.addCondition("summary_date >= ?", startBorn);
		//结束时间
		long endTime = query.getEndTime();
		if(endTime > 0) {
			String endBorn = DateTimeUtil.formatMillis(DateTimeUtil.YYYYMMDD, endTime * 1000L);
			querySet.addCondition("summary_date <= ?", endBorn);
		}
		querySet.orderBy("order by summary_date desc");
		querySet.limit(1, 100);
		querySet.formWhere();
		
		List<PlayerSummary> playerRemains = playerSummaryService.querySummary(querySet);
		Map<Integer, Map<Long, List<PlayerSummary>>> dateChannelMap = ListMapUtil.fillTwoListMap(playerRemains, PlayerSummary::getSummaryDate, PlayerSummary::getChannelId);
		
		Map<String, PlayerSummaryVo> resultMap = new HashMap<>();
		
		for(Entry<Integer, Map<Long, List<PlayerSummary>>> dateChannelEntry : dateChannelMap.entrySet()) {
			int summaryDate = dateChannelEntry.getKey();
			Map<Long, List<PlayerSummary>> channelMap = dateChannelEntry.getValue();
			
			for(Entry<Long, List<PlayerSummary>> channelEntry : channelMap.entrySet()) {
				long channelId = channelEntry.getKey();
				GameChannel gameChannel = gameChannelService.getEntity(0, channelId);
				String key = summaryDate + "_" + channelId;
				
				PlayerSummaryVo resultVo = new PlayerSummaryVo();
				resultVo.setDate(summaryDate);
				if(gameChannel != null) {
					resultVo.setChannelInfo(gameChannel.getName() + "[" + channelId + "]");
				} else {
					resultVo.setChannelInfo("");
				}
				
				for(PlayerSummary playerSummary : channelEntry.getValue()) {
					resultVo.setNewPlayerCount(resultVo.getNewPlayerCount() + playerSummary.getNewPlayerCount());
					resultVo.setPlayerDAU(resultVo.getPlayerDAU() + playerSummary.getPlayerDau());
					resultVo.setTotalPay(resultVo.getTotalPay() + playerSummary.getTotalPay());
					resultVo.setPayPlayerCount(resultVo.getPayPlayerCount() + playerSummary.getPayPlayerCount());
					resultVo.setNewComerPayMoney(resultVo.getNewComerPayMoney() + playerSummary.getNewComerPayMoney());
					resultVo.setNewComerPayCount(resultVo.getNewComerPayCount() + playerSummary.getNewComerPayCount());
					resultVo.setOldComerPayMoney(resultVo.getOldComerPayMoney() + playerSummary.getOldComerPayMoney());
					resultVo.setOldComerPayCount(resultVo.getOldComerPayCount() + playerSummary.getOldComerPayCount());
				}
				//返回单位元
				resultVo.setTotalPay(resultVo.getTotalPay() / 100);
				
				if(resultVo.getPayPlayerCount() > 0) {
					//付费ARPU
					float payArpuF = resultVo.getTotalPay() * 1.0f / resultVo.getPayPlayerCount();
					BigDecimal payArpu = new BigDecimal("" + payArpuF).setScale(2, RoundingMode.UP);
					resultVo.setPayArpu(payArpu.toString());
				}
				
				if(resultVo.getPlayerDAU() > 0) {
					//付费率
					float payRateF = resultVo.getPayPlayerCount() * 1.0f / resultVo.getPlayerDAU() * 100;
					BigDecimal payRate = new BigDecimal("" + payRateF).setScale(2, RoundingMode.UP);
					resultVo.setPayRate(payRate.toString() + "%");
					//活跃ARPU
					float activeArpuF = resultVo.getTotalPay() * 1.0f / resultVo.getPlayerDAU();
					BigDecimal activeArpu = new BigDecimal("" + activeArpuF).setScale(2, RoundingMode.UP);
					resultVo.setActiveArpu(activeArpu.toString());
				}
				if(resultVo.getNewComerPayCount() > 0) {
					//新账号付费ARPU
					float newArpuF = resultVo.getNewComerPayMoney() * 1.0f / resultVo.getNewComerPayCount();
					BigDecimal newArpu = new BigDecimal("" + newArpuF).setScale(2, RoundingMode.UP);
					resultVo.setNewArpu(newArpu.toString());
				}
				if(resultVo.getNewPlayerCount() > 0) {
					//新账号付费率
					float newPayRateF = resultVo.getNewComerPayCount() * 1.0f / resultVo.getNewPlayerCount() * 100;
					BigDecimal newPayRate = new BigDecimal("" + newPayRateF).setScale(2, RoundingMode.UP);
					resultVo.setNewPayRate(newPayRate.toString() + "%");
				}
				
				if(resultVo.getOldComerPayCount() > 0) {
					//老账号付费ARPU
					float oldArpuF = resultVo.getOldComerPayMoney() * 1.0f / resultVo.getOldComerPayCount();
					BigDecimal oldArpu = new BigDecimal("" + oldArpuF).setScale(2, RoundingMode.UP);
					resultVo.setOldArpu(oldArpu.toString());
				}
				if(resultVo.getPlayerDAU() - resultVo.getNewPlayerCount() > 0) {
					//老账号付费率
					float oldPayRateF = resultVo.getOldComerPayCount() * 1.0f / (resultVo.getPlayerDAU() - resultVo.getNewPlayerCount()) * 100;
					BigDecimal oldPayRate = new BigDecimal("" + oldPayRateF).setScale(2, RoundingMode.UP);
					resultVo.setOldPayRate(oldPayRate.toString() + "%");
				}
                resultMap.put(key, resultVo);
			}
		}
		
		List<String> dateChannelKeys = new ArrayList<>(resultMap.keySet());
		Collections.sort(dateChannelKeys);
		
		List<PlayerSummaryVo> resultList = new ArrayList<>();
		for(String bornChannelKey : dateChannelKeys) {
			resultList.add(resultMap.get(bornChannelKey));
		}
		
		PageData<PlayerSummaryVo> pageData = new PageData<>();
		pageData.setCount(resultList.size());
		pageData.setData(resultList);
		return pageData;
	}
	
	@ApiDocument("手动触发当天基础数据（角色）数据统计")
	@RequestMapping(value = "/playerSummary/manual.auth")
	@ResponseBody
	public void manual() {
		playerPayInServerService.countServerRecharge();
		playerSummaryService.countSummary(DateTimeUtil.currMillis() + DateTimeUtil.ONE_DAY_MILLIS);
	}
}
